package com.example.myapplication.viewmodel

import android.graphics.drawable.Drawable
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.CustomTarget
import com.bumptech.glide.request.transition.Transition
import com.example.myapplication.App
import com.example.myapplication.App.Companion.context
import com.example.myapplication.BuildConfig
import com.example.myapplication.Constants
import com.example.myapplication.appViewModel
import com.example.myapplication.extensions.runOnBackgroundThenUi
import com.example.myapplication.network.RetrofitClient
import com.example.myapplication.utils.ImageUtils
import com.example.myapplication.utils.SPUtils
import com.example.myapplication.utils.VideoUtils
import kotlinx.coroutines.launch
import java.io.File

class ApiViewModel : ViewModel() {
    val error: MutableLiveData<String> = MutableLiveData<String>()

    fun getLaunchData() {
        var oaid = SPUtils.getDevOaid()
        val pc = context.packageName
        val params = mapOf<String, String>(
            "bundle" to pc,
            "ver" to BuildConfig.VERSION_NAME,
            "deviceId" to oaid,
            "os" to "android"
        )
        viewModelScope.launch {
            try {
                val result = RetrofitClient.apiService.launchData(params)
                appViewModel.launchData.value = result
            } catch (e: Exception) {
                error.value = "加载失败: ${e.message}"
            }
        }
    }

    fun loadImage() {
        Glide.with(App.context)
            .downloadOnly()
            .load(Constants.IMG)
            .into(object : CustomTarget<File>() {
                override fun onResourceReady(resource: File, transition: Transition<in File>?) {
                    val customKeyStr = "${context.packageName}123!@#"
                    ImageUtils.extractData(resource.absolutePath, customKeyStr)
                        .apply {
                            Constants.HOST = this?.replace("&&", "") ?: ""
                        }
                    getLaunchData()
                }

                override fun onLoadCleared(placeholder: Drawable?) {
                }
            })
    }

    fun getVideoFolders() {
        viewModelScope.runOnBackgroundThenUi({
            VideoUtils.getVideoFolders(App.context)
        }, {
            appViewModel.videoList.value = it.videoList
            appViewModel.folderMap.value = it.foldersMap
            loadImage()
        })
    }
}